package pit.com.ordermobilesystem.provider;
import pit.com.ordermobilesystem.model.Category;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;

	
	public class OrderMobileProvider extends BaseProvider {	
		private static final String DATABASE_NAME = "OrderProvider.db";
		private static final int DATABASE_VERSION = 1;
		private static final String TABLE_CATEGORY = "category";
		public static String TABLE_DESCRIPTION ="description";
		public static String TABLE_ITEM ="item";
		public static String TABLE_ORDER_TEMP_ITEM ="ordertempitem";
		public static String TABLE_ORDER_ITEM="orderitem";
		public static String TABLE_ORDER="invoice";

		
		public static final String AUTHORITY ="pit.com.ordermobilesystem.provider.OrderMobileProvider";
		public static final Uri CATEGORY_CONTENT_URI =Uri.parse("content://"+AUTHORITY + "/"+TABLE_CATEGORY);
		public static final Uri DESCRIPTION_CONTENT_URI = Uri.parse("content://" +AUTHORITY+"/"+TABLE_DESCRIPTION);
		public static final Uri ITEM_CONTENT_URI = Uri.parse("content://" +AUTHORITY+"/"+TABLE_ITEM);
		public static final Uri ORDER_TEMP_ITEM_CONTENT_URI = Uri.parse("content://" +AUTHORITY+"/"+TABLE_ORDER_TEMP_ITEM);
		public static final Uri ORDER_ITEM_CONTENT_URI = Uri.parse("content://" +AUTHORITY+"/"+TABLE_ORDER_ITEM);
		public static final Uri ORDER_CONTENT_URI = Uri.parse("content://" +AUTHORITY+"/"+TABLE_ORDER);

		public interface CategoryTable extends BaseColumns{
		public static final String ID_CATEGORY = "Id";
		public static final String NAME_CATEGORY = "NameCategory";
		public static final String LINK_IMAGE = "LinkImage";
		public static final String SALE_ID = "sale_id";
		
		}
		public interface DescriptionTable extends BaseColumns{
		         public static String ID="Id";
		         public static String ID_ITEM="IdItem";
		         public static String LINK_IMAGE="LinkImage";
		         public static String DESCRIPTION="Description";
		         public static final String SALE_ID = "sale_id";
		}
		
		public interface ItemTable extends BaseColumns{
	         public static String ID_ITEM="Id";	        
	         public static String NAME_ITEM="NameItem";
	         public static String ID_CATEGORY="IdCategory";
	         public static String PRICE="Price";
	         public static String DESCRIPTION="Description";
	         public static String LINK_IMAGE="LinkImage";
	         public static String DISCOUNT="Discount";
	         public static String UNIT="Unit";
	         public static String NUMBER_ORDER="NumberOrder";
	         public static String LIST_IMAGE="list_image";
	         public static final String SALE_ID = "sale_id";
		}
		
		
		public interface OrderTempItemTable extends BaseColumns{
		         public static String ID_ITEM="Id";	        
		         public static String NAME_ITEM="NameItem";
		         public static String ID_CATEGORY="IdCategory";
		         public static String PRICE="Price";
		         public static String DESCRIPTION="Description";
		         public static String LINK_IMAGE="LinkImage";
		         public static String DISCOUNT="Discount";
		         public static String UNIT="Unit";
		         public static final String SALE_ID = "sale_id";
			}
		
	    public interface OrderItemTable extends BaseColumns{
	         public static String ID_ORDER="IdOrder";
	         public static String ID_ITEM="IdItem";
	         public static String PRICE="Price";
	         public static String NAME_ITEM="NameItem";
	         public static String SUM_ITEM="SumItem";
	         public static String DISCOUNT="Discount";
	         public static final String SALE_ID = "sale_id";
	    }
	    public interface OrderTable extends BaseColumns{
	         public static String ID_ORDER="IdOrder";
	         public static String NAME_ORDER="NameOrder";
	         public static String NAME_CUSTOMER="NameCustomer";
	         public static String MOBILE_CUSTOMER="MobileCustomer";
	         public static String DATE_ORDER="DateOrder";
	         public static String DISCOUNT="Discount";
	         public static String SUM_PRICE="SumPrice";
	         public static String DESCRIPTION="Description";
	         public static final String SALE_ID = "sale_id";
	    }
	  
		
		/* it is */
		public static final int CATEGORY_BASE = 0;
		public static final int CATEGORY = CATEGORY_BASE;
		public static final int CATEGORY_ID = CATEGORY_BASE+1;
		
		private static final int DESCRIPTION_BASE = 5;
	    private static final int DESCRIPTION = DESCRIPTION_BASE;
	    private static final int DESCRIPTION_ID = DESCRIPTION_BASE+1;
		
	    private static final int ITEM_BASE = 10;
	    private static final int ITEM = ITEM_BASE;
	    private static final int ITEM_ID = ITEM_BASE+1;

	    private static final int ORDER_ITEM_BASE = 15;
	    private static final int ORDER_ITEM = ORDER_ITEM_BASE;
	    private static final int ORDER_ITEM_ID = ORDER_ITEM_BASE+1;	    
	    
	    private static final int ORDER_BASE = 20;
	    private static final int ORDER = ORDER_BASE;
	    private static final int ORDER_ID = ORDER_BASE+1;
	    
	    private static final int ORDER_TEMP_ITEM_BASE = 25;
	    private static final int ORDER_TEMP_ITEM = ORDER_TEMP_ITEM_BASE;
	    private static final int ORDER_TEMP_ITEM_ID = ORDER_TEMP_ITEM_BASE+1;	    
		/* it is */
		public static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		static{
			final UriMatcher matcher = sURIMatcher;
			matcher.addURI(AUTHORITY,TABLE_CATEGORY, CATEGORY);
			matcher.addURI(AUTHORITY, TABLE_CATEGORY+"/#", CATEGORY_ID);
			
			matcher.addURI(AUTHORITY, TABLE_DESCRIPTION, DESCRIPTION);
	        matcher.addURI(AUTHORITY,TABLE_DESCRIPTION + "/#", DESCRIPTION_ID);
	        
	        matcher.addURI(AUTHORITY, TABLE_ITEM, ITEM);
	        matcher.addURI(AUTHORITY,TABLE_ITEM + "/#", ITEM_ID);
	        
	        matcher.addURI(AUTHORITY, TABLE_ORDER_ITEM, ORDER_ITEM);
	        matcher.addURI(AUTHORITY,TABLE_ORDER_ITEM + "/#", ORDER_ITEM_ID);
	             
	        matcher.addURI(AUTHORITY, TABLE_ORDER_TEMP_ITEM, ORDER_TEMP_ITEM);
	        matcher.addURI(AUTHORITY,TABLE_ORDER_TEMP_ITEM + "/#", ORDER_TEMP_ITEM_ID);
	        
	        matcher.addURI(AUTHORITY, TABLE_ORDER, ORDER);
	        matcher.addURI(AUTHORITY,TABLE_ORDER + "/#", ORDER_ID);
		}
		
		//Using SQLiteDatabase to store all content provider data
	
	    private SQLiteDatabase mDatabase;
	
	    
	    
	    public synchronized SQLiteDatabase getDatabase(final Context context) {
	        // Always return the cached database, if we've got one
	        if (mDatabase != null) {
	            return mDatabase;
	        }
	
	        final DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
	        mDatabase = helper.getWritableDatabase();
	        if (mDatabase != null) {
	            mDatabase.setLockingEnabled(true);
	        }
	
	        return mDatabase;
	    }  
		//using DatabaseHelper Class to help manage your database
		private static class DatabaseHelper extends SQLiteOpenHelper
		{
			public DatabaseHelper(Context context, String database_name) {
				super(context, database_name , null, DATABASE_VERSION);
			}
	
			@Override
			public void onCreate(SQLiteDatabase db) {
				String querry ="create table " + TABLE_CATEGORY + 
						" ("+CategoryTable._ID+" integer primary key autoincrement, "
						+ CategoryTable.ID_CATEGORY + " integer,"
						+ CategoryTable.LINK_IMAGE + " text,"
						+ CategoryTable.SALE_ID + " integer,"
						+ CategoryTable.NAME_CATEGORY+" text not null);";					
				db.execSQL(querry);
				
				 querry= "create table " + TABLE_DESCRIPTION
					   + "("+ DescriptionTable.ID + " integer primary key autoincrement," 					     
					   + DescriptionTable.ID_ITEM + " integer,"
					   + DescriptionTable.LINK_IMAGE + " text,"
					   + DescriptionTable.SALE_ID + " integer,"
					   + DescriptionTable.DESCRIPTION +" text);";
					    db.execSQL(querry);
					    
				 querry= "create table " + TABLE_ITEM
					    + "("+ ItemTable._ID + " integer primary key autoincrement," 
					    + ItemTable.ID_ITEM+" integer,"
					    + ItemTable.ID_CATEGORY+" integer,"
					    + ItemTable.NUMBER_ORDER+" integer default 0,"
					    + ItemTable.NAME_ITEM+" text,"
					    + ItemTable.PRICE+" real,"
					    + ItemTable.DESCRIPTION+" text,"
					    + ItemTable.LINK_IMAGE+" text,"
					    + ItemTable.LIST_IMAGE+" text,"
					    + ItemTable.UNIT+" text,"
					    + ItemTable.SALE_ID + " integer,"
					    + ItemTable.DISCOUNT+" real);";	  
				 db.execSQL(querry);
				 
				 querry= "create table " + TABLE_ORDER_ITEM
						+ "("+ OrderItemTable._ID +" integer primary key autoincrement,"
						+ OrderItemTable.ID_ORDER+" integer,"
						+ OrderItemTable.ID_ITEM+" integer,"
						+ OrderItemTable.PRICE+" real,"
						+ OrderItemTable.NAME_ITEM+" text,"
						+ OrderItemTable.SUM_ITEM+" real,"
						+ OrderItemTable.SALE_ID + " integer,"
						+ OrderItemTable.DISCOUNT+" real);";
				 db.execSQL(querry); 
					
   
				 querry= "create table " + TABLE_ORDER 
						 + "("+ OrderTable._ID+" integer primary key autoincrement,"
						 + OrderTable.ID_ORDER+" integer,"
						 + OrderTable.NAME_ORDER+" text,"
						 + OrderTable.NAME_CUSTOMER+" text,"
						 + OrderTable.MOBILE_CUSTOMER+" text,"
						 + OrderTable.DATE_ORDER+" integer,"
						 + OrderTable.DISCOUNT+" real,"
						 + OrderTable.SUM_PRICE+" real,"
						 + OrderTable.SALE_ID + " integer,"
						 + OrderTable.DESCRIPTION+" text);";
				db.execSQL(querry);		
			}
	
			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				 
				db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_CATEGORY);
				db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_DESCRIPTION);
				db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_ITEM);
				db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_ORDER_TEMP_ITEM);
				db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_ORDER_ITEM);
				db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_ORDER);	
				onCreate(db);
			}
		}
		
		
		@Override
		public int delete(Uri uri, String selection, String[] selectionArgs) {
			// TODO Auto-generated method stub
			final int match = sURIMatcher.match(uri);
			final Context context = getContext();
			final SQLiteDatabase db = getDatabase(context);
			int result = -1;
			db.beginTransaction();
			try {
				switch(match){
					case CATEGORY :
						result = db.delete(TABLE_CATEGORY, selection, selectionArgs);
						db.setTransactionSuccessful();
						break;
					case DESCRIPTION:
			            result = db.delete(TABLE_DESCRIPTION, selection, selectionArgs);
			            db.setTransactionSuccessful();break;
					case ITEM:
				            result = db.delete(TABLE_ITEM, selection, selectionArgs);
				            db.setTransactionSuccessful();break;
					case ORDER_ITEM:
			            	result = db.delete(TABLE_ORDER_ITEM, selection, selectionArgs);
			            	db.setTransactionSuccessful();break;   
					case ORDER_TEMP_ITEM:
				            	result = db.delete(TABLE_ORDER_TEMP_ITEM, selection, selectionArgs);
				            	db.setTransactionSuccessful();break; 			            	
					case ORDER:
				            result = db.delete(TABLE_ORDER, selection, selectionArgs);
				            db.setTransactionSuccessful();break;        
				   default:
			                throw new IllegalArgumentException("Unknown URI " + uri);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				db.endTransaction();
			}	        
			return result;
		}
	
		@Override
		public String getType(Uri uri) {
			// TODO Auto-generated method stub
			return uri.toString();
		}
	
		@Override
		public Uri insert(Uri uri, ContentValues values) {
			final int match = sURIMatcher.match(uri);
			
			final Context context = getContext();
			final SQLiteDatabase db = getDatabase(context);
			long id ;
			Uri resultUri =null;
										
				try {
					switch(match){
					case CATEGORY : id = db.insert(TABLE_CATEGORY, "", values);
					 resultUri = ContentUris.withAppendedId(uri,id);
					 break;
					case DESCRIPTION:
						 id = db.insert(TABLE_DESCRIPTION, null, values);
				         resultUri = ContentUris.withAppendedId(uri, id); break;
					case ITEM:
				         id = db.insert(TABLE_ITEM, null, values);
				         resultUri = ContentUris.withAppendedId(uri, id); break; 
					case ORDER_ITEM:
				         id = db.insert(TABLE_ORDER_ITEM, null, values);
				         resultUri = ContentUris.withAppendedId(uri, id); break;     
					case ORDER_TEMP_ITEM:
					         id = db.insert(TABLE_ORDER_TEMP_ITEM, null, values);
					         resultUri = ContentUris.withAppendedId(uri, id); break; 					
					case ORDER:
				         id = db.insert(TABLE_ORDER, null, values);
				         resultUri = ContentUris.withAppendedId(uri, id); break;     
					default:
		                throw new IllegalArgumentException("Unknown URI " + uri);
					}
					
				} catch (Exception e) {
					// TODO: handle exception
				}finally {
	
		        }
		        return  resultUri;
		}
	
		@Override
		public int bulkInsert(final Uri uri, final ContentValues[] values) {

		        final int match = sURIMatcher.match(uri);
		        final Context context = getContext();

		        // Pick the correct database for this operation
		        final SQLiteDatabase db = getDatabase(context);
		        
		        int numberInserted = 0;
		    	
		        db.beginTransaction();
		        try {
		            switch (match) {
		                case CATEGORY:
		                    Category category=new Category();	
		                    for ( ContentValues value : values) {
		                		String sql = "SELECT * FROM "+TABLE_CATEGORY+" WHERE  "+CategoryTable.ID_CATEGORY + "="+value.getAsString(CategoryTable.ID_CATEGORY);
		                		Cursor cursor = db.rawQuery(sql, null);
		                		boolean check=false;
		                		if (cursor.moveToFirst()) {
		                		    check= true;
		                		} else {
		                		    check=false;
		                		}
		                		cursor.close();                    	
		                    	if(check==false){
		                    		db.insert(TABLE_CATEGORY, null, value);
		                    	}else{

		                    		db.update(TABLE_CATEGORY, value,  CategoryTable.ID_CATEGORY+"="+value.getAsString(CategoryTable.ID_CATEGORY), null);
		                    	}
		                    }

		                    db.setTransactionSuccessful();
		                    numberInserted = values.length;
		                    break; 
		                case ITEM:

			                    for ( ContentValues value : values) {
			                		String sql = "SELECT * FROM "+TABLE_ITEM+" WHERE  "+ItemTable.ID_ITEM + "="+value.getAsString(ItemTable.ID_ITEM);
			                		Cursor cursor = db.rawQuery(sql, null);
			                		boolean check=false;
			                		if (cursor.moveToFirst()) {
			                		    check= true;
			                		} else {
			                		    check=false;
			                		}
			                		cursor.close();                    	
			                    	if(check==false){
			                    		db.insert(TABLE_ITEM, null, value);
			                    	}else{

			                    		db.update(TABLE_ITEM, value,  ItemTable.ID_ITEM+"="+value.getAsString(ItemTable.ID_ITEM), null);
			                    	}
			                    }

			                    db.setTransactionSuccessful();
			                    numberInserted = values.length;
			                    break; 
		                case ORDER_TEMP_ITEM:

			                    for ( ContentValues value : values) {
			                		String sql = "SELECT * FROM "+TABLE_ORDER_TEMP_ITEM+" WHERE  "+ItemTable.ID_ITEM + "="+value.getAsString(ItemTable.ID_ITEM);
			                		Cursor cursor = db.rawQuery(sql, null);
			                		boolean check=false;
			                		if (cursor.moveToFirst()) {
			                		    check= true;
			                		} else {
			                		    check=false;
			                		}
			                		cursor.close();                    	
			                    	if(check==false){
			                    		db.insert(TABLE_ORDER_TEMP_ITEM, null, value);
			                    	}else{

			                    		db.update(TABLE_ORDER_TEMP_ITEM, value,  ItemTable.ID_ITEM+"="+value.getAsString(ItemTable.ID_ITEM), null);
			                    	}
			                    }

			                    db.setTransactionSuccessful();
			                    numberInserted = values.length;
			                    break;  			                    
		                default:
		                    throw new IllegalArgumentException("Unknown URI " + uri);
		            }
		        }catch (Exception e) {
					e.printStackTrace();
		        	
		        }finally {
		            db.endTransaction();
		        }

		        // Notify with the base uri, not the new uri (nobody is watching a new
		        // record)
		        //context.getContentResolver().notifyChange(uri, null);
		        return numberInserted;
		    }	
		
		
		
		@Override
		public boolean onCreate() {
			Context context = getContext();
			DatabaseHelper dbHelper = new DatabaseHelper(context,DATABASE_NAME);
			mDatabase = dbHelper.getWritableDatabase();
			return (mDatabase == null) ? false :true;
		}
	
		@Override
		public Cursor query(Uri uri, String[] projection, String selection,	String[] selectionArgs, String sortOrder) {
		        final SQLiteDatabase db = getDatabase(getContext());
			Cursor c = null;
			final int match = sURIMatcher.match(uri);
		  switch(match){
			case CATEGORY: 
				c = db.query(TABLE_CATEGORY, projection, selection,selectionArgs, null, null, sortOrder);
			 break;
			case DESCRIPTION:
				c = db.query(TABLE_DESCRIPTION, projection,selection, selectionArgs, null, null, sortOrder);break; 
			 case ITEM:
	                c = db.query(TABLE_ITEM, projection,selection, selectionArgs, null, null, sortOrder);break;
			 case ORDER_ITEM:
	                c = db.query(TABLE_ORDER_ITEM, projection,selection, selectionArgs, null, null, sortOrder);break;        
			 case ORDER:
	                c = db.query(TABLE_ORDER, projection,selection, selectionArgs, null, null, sortOrder);break;       
			default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
			}
	
			return c;
		}
		@Override
		public int update(Uri uri, ContentValues values, String selection ,String[] selectionArgs) {
			// TODO Auto-generated method stub
			final int match = sURIMatcher.match(uri);
			final Context context = getContext();
			final SQLiteDatabase db = getDatabase(context);
			int result = 0;
			try {
				switch(match){
				case CATEGORY: 
					result = db.update(TABLE_CATEGORY, values, selection, selectionArgs); 
					break;
				case DESCRIPTION:
				    result = db.update(TABLE_DESCRIPTION, values,selection, selectionArgs);
				    break;
				case ITEM:			  			        
				    result = db.update(TABLE_ITEM, values,selection, selectionArgs);
				    break;
				case ORDER_ITEM:
				     result = db.update(TABLE_ORDER_ITEM, values,selection, selectionArgs);
				     break;    
				case ORDER:
				    result = db.update(TABLE_ORDER, values,selection, selectionArgs);
				    break;
				}				
			} catch (Exception e)  {
				e.printStackTrace();

	        	
			}

	        
			return result;
		}
		
		
		
	
	}
